
package org.aha.ahaxproject.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.servlet.WebAppUser;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class MyServlet extends HttpServlet
{
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException
  {
    WebAppUser wau=authenticate(req, resp);
    
    if (wau!=null)
    {
      resp.setContentType("text/html");
      PrintWriter pw=resp.getWriter();
      
      pw.println("<h1>Welcome "+wau+" to Aha's X Project</h1>");
      pw.println("<br /><br /><br />");
      pw.println("<a href='"+wau.getLogoutUrl()+"'>Log Out</a>");
    }
  }
  
  private WebAppUser authenticate(HttpServletRequest req, 
    HttpServletResponse resp) throws IOException
  {
    String thisURL=req.getRequestURI();
    
    UserService us=UserServiceFactory.getUserService();
    
    Principal principal=req.getUserPrincipal();
    if (principal==null)
    {
      resp.setContentType("text/html");
      PrintWriter pw=resp.getWriter();
      
      StringBuilder sb=new StringBuilder();
      
      pw.println("<html><body>");
      pw.println("<h1>Welcome to Aha's eXperimental Project</h1>");
     
      String lurl=us.createLoginURL(thisURL);
      
      sb.append("<h2><a href='").append(lurl)
        .append("'>Login Using Your Google Account</a></h2>");
      
      pw.println(sb);
      
      return null;
    }
    else
    {
      return new WebAppUser().setName(principal.getName())
                             .setLogoutUrl(us.createLogoutURL(thisURL));
    }
  }
  
}
